import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Card, Button, Descriptions, Tag, Steps, Divider, Modal, message } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import styled from 'styled-components';
import MainLayout from '../../components/Layout/MainLayout';
import { getOrderDetail, cancelOrder } from '../../api/orderApi';
import { Order } from '../../api/types';

const { Step } = Steps;
const { confirm } = Modal;

const PageContainer = styled.div`
  padding: 20px 0;
`;

const TitleSection = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
`;

const OrderTitle = styled.h2`
  font-size: 22px;
  margin: 0;
`;

const ButtonGroup = styled.div`
  button {
    margin-left: 10px;
  }
`;

const StepsContainer = styled.div`
  margin: 30px 0;
`;

const StatusTag = {
  pending: <Tag color="blue">待支付</Tag>,
  confirmed: <Tag color="green">已确认</Tag>,
  cancelled: <Tag color="red">已取消</Tag>,
  completed: <Tag color="purple">已完成</Tag>
};

const OrderDetailPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  
  const [order, setOrder] = useState<Order | null>(null);
  const [loading, setLoading] = useState(true);
  
  // 获取订单详情
  useEffect(() => {
    const fetchOrderDetail = async () => {
      if (!id) return;
      
      setLoading(true);
      try {
        const response = await getOrderDetail(id);
        setOrder(response.data);
      } catch (error) {
        console.error('获取订单详情失败', error);
        message.error('订单信息加载失败');
      } finally {
        setLoading(false);
      }
    };
    
    fetchOrderDetail();
  }, [id]);
  
  // 处理取消订单
  const handleCancelOrder = () => {
    if (!order) return;
    
    confirm({
      title: '确定要取消订单吗?',
      icon: <ExclamationCircleOutlined />,
      content: '取消后需要重新预订',
      okText: '确认取消',
      okType: 'danger',
      cancelText: '再想想',
      async onOk() {
        try {
          await cancelOrder(order.id);
          message.success('订单已成功取消');
          
          // 刷新订单数据
          const response = await getOrderDetail(order.id);
          setOrder(response.data);
        } catch (error) {
          console.error('取消订单失败', error);
          message.error('订单取消失败，请重试');
        }
      }
    });
  };
  
  // 处理支付订单
  const handlePayOrder = () => {
    message.success('支付功能暂未实现，下次一定！');
  };
  
  // 获取订单流程步骤
  const getOrderStep = (status: string) => {
    switch (status) {
      case 'pending':
        return 0;
      case 'confirmed':
        return 1;
      case 'completed':
        return 2;
      case 'cancelled':
        return -1;
      default:
        return 0;
    }
  };
  
  if (loading) {
    return (
      <MainLayout>
        <div style={{ textAlign: 'center', padding: '100px 0' }}>加载中...</div>
      </MainLayout>
    );
  }
  
  if (!order) {
    return (
      <MainLayout>
        <div style={{ textAlign: 'center', padding: '100px 0' }}>
          <h2>未找到订单信息</h2>
          <Button type="primary" onClick={() => navigate('/profile')}>返回个人中心</Button>
        </div>
      </MainLayout>
    );
  }
  
  const orderStep = getOrderStep(order.status);
  
  return (
    <MainLayout>
      <PageContainer className="container">
        <Card>
          <TitleSection>
            <OrderTitle>
              订单详情 
              {StatusTag[order.status as keyof typeof StatusTag]}
            </OrderTitle>
            <ButtonGroup>
              {order.status === 'pending' && (
                <>
                  <Button danger onClick={handleCancelOrder}>取消订单</Button>
                  <Button type="primary" onClick={handlePayOrder}>立即支付</Button>
                </>
              )}
              {order.status === 'confirmed' && (
                <Button danger onClick={handleCancelOrder}>取消订单</Button>
              )}
              <Button onClick={() => navigate('/profile')}>返回个人中心</Button>
            </ButtonGroup>
          </TitleSection>
          
          {order.status !== 'cancelled' && (
            <StepsContainer>
              <Steps current={orderStep}>
                <Step title="提交订单" description="等待付款" />
                <Step title="订单确认" description="等待入住" />
                <Step title="完成" description="入住完成" />
              </Steps>
            </StepsContainer>
          )}
          
          <Divider />
          
          <Descriptions title="预订信息" bordered column={{ xxl: 4, xl: 3, lg: 3, md: 3, sm: 2, xs: 1 }}>
            <Descriptions.Item label="订单编号">{order.id}</Descriptions.Item>
            <Descriptions.Item label="订单状态">
              {StatusTag[order.status as keyof typeof StatusTag]}
            </Descriptions.Item>
            <Descriptions.Item label="创建时间">{order.createTime}</Descriptions.Item>
            <Descriptions.Item label="酒店名称">{order.hotelName}</Descriptions.Item>
            <Descriptions.Item label="房型">{order.roomName}</Descriptions.Item>
            <Descriptions.Item label="入住人">{order.guestName}</Descriptions.Item>
            <Descriptions.Item label="联系电话">{order.contactPhone}</Descriptions.Item>
            <Descriptions.Item label="入住日期">{order.checkInDate}</Descriptions.Item>
            <Descriptions.Item label="离店日期">{order.checkOutDate}</Descriptions.Item>
            <Descriptions.Item label="住宿天数">{order.nights}晚</Descriptions.Item>
            <Descriptions.Item label="入住人数">{order.guests}人</Descriptions.Item>
          </Descriptions>
          
          <Divider />
          
          <Descriptions title="费用信息" bordered column={{ xxl: 4, xl: 3, lg: 3, md: 3, sm: 2, xs: 1 }}>
            <Descriptions.Item label="房费总额">¥{order.totalPrice}</Descriptions.Item>
            {order.discountPrice && (
              <Descriptions.Item label="优惠金额">-¥{order.discountPrice}</Descriptions.Item>
            )}
            <Descriptions.Item label="实付金额">
              <span style={{ color: '#ff4d4f', fontWeight: 'bold' }}>
                ¥{order.finalPrice}
              </span>
            </Descriptions.Item>
            {order.couponId && (
              <Descriptions.Item label="使用优惠券">是</Descriptions.Item>
            )}
          </Descriptions>
        </Card>
      </PageContainer>
    </MainLayout>
  );
};

export default OrderDetailPage; 